package com.zhanghe.study.thread.aqs;

import java.util.concurrent.CountDownLatch;

/**
 * 在完成某些运算时，只有其他所有线程全部完成运算时，当前运算才会继续
 * @author zh
 * @date 2021/2/6 12:42
 */
public class TestCountDownLatch {

    public static void main(String[] args) {
        // 声明数量
        CountDownLatch latch = new CountDownLatch(5);
        LatchDemo latchDemo = new LatchDemo(latch);

        long start = System.currentTimeMillis();

        for (int i = 0;i<5;i++){
            new Thread(latchDemo).start();
        }

        try {
            // 阻塞一直到减至0时
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("累计耗时"+(System.currentTimeMillis() - start));

    }
}

class LatchDemo implements Runnable{

    private CountDownLatch latch;

    public LatchDemo(CountDownLatch latch){
        this.latch = latch;
    }

    @Override
    public void run() {
        try{
            for(int i = 0;i<10;i++){
                System.out.println(i);
            }
        } finally {
            // 减一表示完成
            latch.countDown();
        }
    }
}
